/**
 * Created by PKD on 2018/4/7.
 */
var DBFactory = require('../db/mysql_db');
var shortUrlDao = module.exports;

function insertShortUrl(data, callback) {

    if(!data.hasOwnProperty('uid_own')) data.uid_own = 0;
    var sql = "Replace into short_url(`key`, url, uid_own) values (?);";
    var value = [data.key, data.url, data.uid_own];
    DBFactory.poolQuery(sql, [value], function () {
        callback('no avail connection');
        return;
    }, function (error, result) {
        if(error){
            callback(error, null);
            return;
        }
        callback(null, '绑定成功');
    });
}
//添加代理
shortUrlDao.setUrl = function(data,callback) {
    if(!data || !data.key) {
        callback(new Error(500));
        return;
    }
    var sql = "select url from short_url where `key` = ? limit 1";
    var value = [data.key];
    DBFactory.poolQuery(sql, value, function () {
        callback('no avail connection');
        return;
    }, function (error, result) {
        if(error){
            callback(error, null);
            return;
        }
        if(result && result.length > 0){
            callback('链接已经设置过，二维码已被绑定！');
            return;
        }
        insertShortUrl(data, callback);
    });
}

//添加代理
shortUrlDao.getUrl = function(data, callback) {
    if(!data || !data.key ) {
        callback(new Error(500));
        return;
    }
    var sql = "select url from short_url where `key` = ? limit 1";
    var value = [data.key];
    DBFactory.poolQuery(sql, value, function () {
        callback('no avail connection');
        return;
    }, function (error, result) {
        if(error){
            callback(error, null);
            return;
        }
        callback(null, result);
    });
}
